﻿using System;
using System.Threading.Tasks;

using Uber.Storage;
using Uber.HabboHotel.GameClients;
using System.Threading;

namespace Uber.HabboHotel.Misc
{
    public class LowPriorityWorker
    {
        private Task Worker;

        public LowPriorityWorker()
        {
            this.Worker = null;
            this.Worker = new Task(Process, CancellationToken.None, TaskCreationOptions.LongRunning);
        }

        public void Start()
        {
            this.Worker.Start();
        }

        public void Stop()
        {
            this.Worker.Wait();
            this.Worker.Dispose();
            this.Worker = null;
        }

        public void Process()
        {
            while (true)
            {
                #region Save Chatlogs
                try
                {
                    UberEnvironment.GetGame().GetChatlogsManager().PurgeChatlogs();
                    UberEnvironment.GetGame().GetChatlogsManager().Save();
                }
                catch { }

                if (UberEnvironment.GetGame().GetIdGenerator().NeedsUpdate)
                {
                    UberEnvironment.GetGame().GetIdGenerator().Initialize();
                }

                #endregion

                #region Statistics
                int Status = 1;
                int UsersOnline = UberEnvironment.GetGame().GetClientManager().ClientCount;
                int RoomsLoaded = UberEnvironment.GetGame().GetRoomManager().LoadedRoomsCount;

                using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
                {
                    dbClient.ExecuteQuery("UPDATE server_status SET stamp = '" + UberEnvironment.GetUnixTimestamp() + "', status = '" + Status + "', users_online = '" + UsersOnline + "', rooms_loaded = '" + RoomsLoaded + "', server_ver = '" + UberEnvironment.PrettyVersion + "' LIMIT 1");
                }
                #endregion

                #region Effects
                UberEnvironment.GetGame().GetClientManager().CheckEffects();
                #endregion

                #region Worker
                if (Worker != null /*|| (!Worker.IsCanceled)*/)
                {
                    this.Worker.Wait(15000);
                }
                #endregion
            }
        }
    }
}